package logic

import (
	"context"
	"fmt"
	"mall/model/mysql"
	"mall/model/redis"
	"mall/pkg"

	"mall/mallrpc/internal/svc"
	"mall/mallrpc/mallrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdatePasswordLogic {
	return &UserUpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdatePasswordLogic) UserUpdatePassword(in *mallrpc.UserUpdatePasswordRequest) (*mallrpc.UserUpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSmsupdatepassword" + in.Tel)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("验证码错误，请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Model(&mysql.User{}).Where("tel=?", in.Tel).First(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	if user.Password != pkg.Pwdmd5(in.Password) {
		return nil, fmt.Errorf("旧密码错误，请重新输入")
	}
	if in.Password == in.Password1 {
		return nil, fmt.Errorf("旧密码与新密码不能一样")
	}
	user.Password = pkg.Pwdmd5(in.Password1)
	mysql.DB.Debug().Updates(&user)
	redis.Client.Del("sendSmsupdatepassword" + in.Tel)

	return &mallrpc.UserUpdatePasswordResponse{Id: int64(user.ID)}, nil
}
